"use client";

import React, { useState, useEffect, useRef } from "react";
import "bootstrap/dist/css/bootstrap.min.css";

export default function ConnectModal({
  isOpen,
  onClose,
  onSubmit,
  isDarkMode,
}) {
  const [formData, setFormData] = useState({
    host: "",
    port: "3306",
    username: "",
    password: "",
    database: "",
    connectionName: "",
  });

  const [connectionString, setConnectionString] = useState("");
  const [errors, setErrors] = useState({});
  const textareaRef = useRef(null);

  // 重置表单数据
  const resetForm = () => {
    setFormData({
      host: "",
      port: "3306",
      username: "",
      password: "",
      database: "",
      connectionName: "",
    });
    setConnectionString("");
    setErrors({});
  };

  // 清空表单数据（保留端口）
  const clearForm = () => {
    setFormData((prev) => ({
      host: "",
      port: prev.port, // 保留端口值
      username: "",
      password: "",
      database: "",
      connectionName: "",
    }));
    setErrors({});
  };

  // 当Modal关闭时重置表单
  useEffect(() => {
    if (!isOpen) {
      resetForm();
    }
  }, [isOpen]);

  // 解析JDBC连接字符串
  const parseConnectionString = (connStr) => {
    try {
      // 支持多种JDBC连接字符串格式
      // jdbc:mysql://host:port/database?user=username&password=password
      // jdbc:mysql://host:port/database
      // jdbc:mysql://host/database?user=username&password=password

      let cleanStr = connStr.trim();

      // 检查是否是JDBC MySQL连接串
      if (!cleanStr.startsWith("jdbc:mysql://")) {
        throw new Error("请输入有效的JDBC MySQL连接字符串");
      }

      // 移除jdbc:mysql://前缀
      cleanStr = cleanStr.substring(13);

      // 解析主要部分和参数部分
      const [mainPart, paramsPart] = cleanStr.split("?");

      // 解析主要部分: host:port/database 或 host/database
      const hostDbMatch = mainPart.match(/^([^:\/]+)(?::(\d+))?\/(.+)$/);

      if (!hostDbMatch) {
        throw new Error("连接字符串格式不正确");
      }

      const [, host, port, database] = hostDbMatch;

      let username = "";
      let password = "";

      // 解析参数部分
      if (paramsPart) {
        const params = new URLSearchParams(paramsPart);
        username = params.get("user") || "";
        password = params.get("password") || "";
      }

      return {
        username: username,
        password: password,
        host: host || "",
        port: port || "3306",
        database: database || "",
      };
    } catch (error) {
      console.error("解析连接字符串失败:", error);
      return null;
    }
  };

  // 处理连接字符串变化
  const handleConnectionStringChange = (e) => {
    const value = e.target.value;
    setConnectionString(value);

    if (value.trim()) {
      const parsed = parseConnectionString(value);
      if (parsed) {
        setFormData((prev) => ({
          ...prev,
          ...parsed,
        }));
        setErrors({});
      } else {
        setErrors({ connectionString: "连接字符串格式不正确" });
      }
    } else {
      // 当连接字符串清空时，清空表单（保留端口）
      clearForm();
    }
  };

  // 自动伸缩textarea高度，确保视觉协调
  useEffect(() => {
    const el = textareaRef.current;
    if (!el) return;
    el.style.height = "auto";
    const min = 80; // 与CSS中最小高度一致
    const max = 160; // 限制最大高度，避免过高
    const newH = Math.min(Math.max(el.scrollHeight, min), max);
    el.style.height = `${newH}px`;
  }, [connectionString]);

  // 处理表单字段变化
  const handleInputChange = (field, value) => {
    setFormData((prev) => ({
      ...prev,
      [field]: value,
    }));

    // 清除对应字段的错误
    if (errors[field]) {
      setErrors((prev) => ({
        ...prev,
        [field]: "",
      }));
    }
  };

  // 表单验证
  const validateForm = () => {
    const newErrors = {};

    if (!formData.host.trim()) {
      newErrors.host = "主机地址不能为空";
    }

    if (!formData.port.trim()) {
      newErrors.port = "端口不能为空";
    } else if (
      !/^\d+$/.test(formData.port) ||
      parseInt(formData.port) < 1 ||
      parseInt(formData.port) > 65535
    ) {
      newErrors.port = "端口必须是1-65535之间的数字";
    }

    if (!formData.username.trim()) {
      newErrors.username = "用户名不能为空";
    }

    if (!formData.database.trim()) {
      newErrors.database = "数据库名不能为空";
    }

    if (!formData.connectionName.trim()) {
      newErrors.connectionName = "连接名称不能为空";
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  // 处理提交
  const handleSubmit = (e) => {
    e.preventDefault();

    if (validateForm()) {
      onSubmit(formData);
      onClose();
    }
  };

  // 处理取消
  const handleCancel = () => {
    onClose();
  };

  if (!isOpen) return null;

  return (
    <div className={`modal-overlay ${isDarkMode ? "dark" : "light"}`}>
      <div className={`modal-container ${isDarkMode ? "dark" : "light"}`}>
        <div className="modal-header">
          <h4 className="modal-title">
            <span className="title-icon">🔗</span>
            添加数据库连接
          </h4>
          <button
            type="button"
            className="close-btn"
            onClick={handleCancel}
            aria-label="关闭"
          >
            ✕
          </button>
        </div>

        <div className="modal-body">
          <form onSubmit={handleSubmit}>
            {/* 连接字符串识别区域 */}
            <div
              className="connection-string-section"
              onClick={() => {
                // 点击时聚焦到textarea
                if (textareaRef.current) {
                  textareaRef.current.focus();
                }
              }}
              style={{ cursor: "pointer" }}
            >
              <label className="form-label connection-string-label">
                <span className="label-icon">🔍</span>
                快速连接（JDBC连接字符串）
                <span className="label-badge">智能解析</span>
              </label>

              <div className="connection-input-wrapper">
                <textarea
                  className={`form-control connection-string-input ${
                    errors.connectionString ? "is-invalid" : ""
                  } ${connectionString ? "has-content" : ""}`}
                  placeholder="jdbc:mysql://localhost:3306/database?user=username&password=password&#10;或&#10;jdbc:mysql://localhost/database?user=username&password=password"
                  value={connectionString}
                  onChange={handleConnectionStringChange}
                  rows={3}
                  spellCheck={false}
                  autoComplete="off"
                  ref={textareaRef}
                />
                {/* 输入状态指示器 */}
                <div className="input-status-indicator">
                  {connectionString && !errors.connectionString && (
                    <span className="status-success">
                      <span className="status-icon">✓</span>
                      已识别
                    </span>
                  )}
                  {errors.connectionString && (
                    <span className="status-error">
                      <span className="status-icon">⚠</span>
                      格式错误
                    </span>
                  )}
                </div>
              </div>

              {errors.connectionString && (
                <div className="invalid-feedback enhanced-error">
                  <span className="error-icon">❌</span>
                  {errors.connectionString}
                </div>
              )}

              <div className="form-help">
                <span className="help-icon">💡</span>
                <span className="help-text">
                  输入完整的JDBC连接字符串，系统将自动解析并填充下方表单
                </span>
              </div>
            </div>

            <div className="divider">
              <span>或手动填写</span>
            </div>

            {/* 手动填写表单 */}
            <div className="row">
              <div className="col-md-6">
                <div className="form-group">
                  <label className="form-label required">
                    <span className="label-icon">🏠</span>
                    主机地址
                  </label>
                  <input
                    type="text"
                    className={`form-control ${
                      errors.host ? "is-invalid" : ""
                    }`}
                    placeholder="localhost 或 IP地址"
                    value={formData.host}
                    onChange={(e) => handleInputChange("host", e.target.value)}
                  />
                  {errors.host && (
                    <div className="invalid-feedback">{errors.host}</div>
                  )}
                </div>
              </div>
              <div className="col-md-6">
                <div className="form-group">
                  <label className="form-label required">
                    <span className="label-icon">🔌</span>
                    端口
                  </label>
                  <input
                    type="text"
                    className={`form-control ${
                      errors.port ? "is-invalid" : ""
                    }`}
                    placeholder="3306"
                    value={formData.port}
                    onChange={(e) => handleInputChange("port", e.target.value)}
                  />
                  {errors.port && (
                    <div className="invalid-feedback">{errors.port}</div>
                  )}
                </div>
              </div>
            </div>

            <div className="row">
              <div className="col-md-6">
                <div className="form-group">
                  <label className="form-label required">
                    <span className="label-icon">👤</span>
                    用户名
                  </label>
                  <input
                    type="text"
                    className={`form-control ${
                      errors.username ? "is-invalid" : ""
                    }`}
                    placeholder="数据库用户名"
                    value={formData.username}
                    onChange={(e) =>
                      handleInputChange("username", e.target.value)
                    }
                  />
                  {errors.username && (
                    <div className="invalid-feedback">{errors.username}</div>
                  )}
                </div>
              </div>
              <div className="col-md-6">
                <div className="form-group">
                  <label className="form-label">
                    <span className="label-icon">🔒</span>
                    密码
                  </label>
                  <input
                    type="password"
                    className="form-control"
                    placeholder="数据库密码（可选）"
                    value={formData.password}
                    onChange={(e) =>
                      handleInputChange("password", e.target.value)
                    }
                  />
                </div>
              </div>
            </div>

            <div className="row">
              <div className="col-md-6">
                <div className="form-group">
                  <label className="form-label required">
                    <span className="label-icon">🗄️</span>
                    数据库名
                  </label>
                  <input
                    type="text"
                    className={`form-control ${
                      errors.database ? "is-invalid" : ""
                    }`}
                    placeholder="数据库名称"
                    value={formData.database}
                    onChange={(e) =>
                      handleInputChange("database", e.target.value)
                    }
                  />
                  {errors.database && (
                    <div className="invalid-feedback">{errors.database}</div>
                  )}
                </div>
              </div>
              <div className="col-md-6">
                <div className="form-group">
                  <label className="form-label required">
                    <span className="label-icon">📝</span>
                    连接名称
                  </label>
                  <input
                    type="text"
                    className={`form-control ${
                      errors.connectionName ? "is-invalid" : ""
                    }`}
                    placeholder="为此连接起个名字"
                    value={formData.connectionName}
                    onChange={(e) =>
                      handleInputChange("connectionName", e.target.value)
                    }
                  />
                  {errors.connectionName && (
                    <div className="invalid-feedback">
                      {errors.connectionName}
                    </div>
                  )}
                </div>
              </div>
            </div>
          </form>
        </div>

        <div className="modal-footer">
          <button
            type="button"
            className="btn btn-secondary"
            onClick={handleCancel}
          >
            取消
          </button>
          <button
            type="button"
            className="btn btn-outline-secondary"
            onClick={clearForm}
            style={{ marginLeft: "8px" }}
          >
            <span className="btn-icon">🔄</span>
            重置
          </button>
          <button
            type="button"
            className="btn btn-primary"
            onClick={handleSubmit}
            style={{ marginLeft: "8px" }}
          >
            <span className="btn-icon">🔗</span>
            连接
          </button>
        </div>
      </div>

      <style jsx>{`
        .modal-overlay {
          position: fixed;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background: rgba(0, 0, 0, 0.6);
          display: flex;
          align-items: center;
          justify-content: center;
          z-index: 1050;
          backdrop-filter: blur(4px);
          animation: fadeIn 0.2s ease-out;
        }

        @keyframes fadeIn {
          from {
            opacity: 0;
          }
          to {
            opacity: 1;
          }
        }

        .modal-container {
          width: 90%;
          max-width: 600px;
          max-height: 90vh;
          border-radius: 12px;
          box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
          overflow: hidden;
          animation: slideIn 0.3s ease-out;
        }

        @keyframes slideIn {
          from {
            transform: translateY(-20px) scale(0.95);
            opacity: 0;
          }
          to {
            transform: translateY(0) scale(1);
            opacity: 1;
          }
        }

        .modal-container.light {
          background: #fff;
          color: #333;
        }

        .modal-container.dark {
          background: #2d2d2d;
          color: #fff;
        }

        .modal-header {
          padding: 20px 24px;
          border-bottom: 1px solid var(--border-color);
          display: flex;
          align-items: center;
          justify-content: space-between;
        }

        .light .modal-header {
          background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
          border-bottom-color: #dee2e6;
        }

        .dark .modal-header {
          background: linear-gradient(135deg, #404040 0%, #353535 100%);
          border-bottom-color: #555;
        }

        .modal-title {
          margin: 0;
          font-size: 1.25rem;
          font-weight: 600;
          display: flex;
          align-items: center;
          gap: 8px;
        }

        .title-icon {
          font-size: 1.1rem;
        }

        .close-btn {
          background: none;
          border: none;
          font-size: 1.5rem;
          cursor: pointer;
          padding: 4px 8px;
          border-radius: 4px;
          transition: all 0.2s ease;
          line-height: 1;
        }

        .light .close-btn {
          color: #6c757d;
        }

        .dark .close-btn {
          color: #adb5bd;
        }

        .close-btn:hover {
          background: rgba(255, 0, 0, 0.1);
          color: #dc3545;
          transform: scale(1.1);
        }

        .modal-body {
          padding: 24px;
          max-height: 60vh;
          overflow-y: auto;
          /* 优化滚动性能 */
          -webkit-overflow-scrolling: touch; /* iOS平滑滚动 */
          scroll-behavior: smooth; /* 平滑滚动行为 */
          transform: translateZ(0); /* 启用硬件加速 */
          will-change: scroll-position; /* 优化滚动性能 */
          /* 自定义滚动条样式 */
          scrollbar-width: thin;
          scrollbar-color: var(--scrollbar-thumb) var(--scrollbar-track);
        }

        /* Webkit浏览器滚动条样式 */
        .modal-body::-webkit-scrollbar {
          width: 8px;
        }

        .modal-body::-webkit-scrollbar-track {
          background: var(--scrollbar-track);
          border-radius: 4px;
        }

        .modal-body::-webkit-scrollbar-thumb {
          background: var(--scrollbar-thumb);
          border-radius: 4px;
          transition: background-color 0.2s ease;
        }

        .modal-body::-webkit-scrollbar-thumb:hover {
          background: var(--scrollbar-thumb-hover);
        }

        /* 滚动条在不同主题下的颜色 */
        .light .modal-body {
          --scrollbar-track: #f1f3f4;
          --scrollbar-thumb: #c1c1c1;
          --scrollbar-thumb-hover: #a8a8a8;
        }

        .dark .modal-body {
          --scrollbar-track: #404040;
          --scrollbar-thumb: #666;
          --scrollbar-thumb-hover: #777;
        }

        .connection-string-section {
          margin-bottom: 24px;
          padding: 16px;
          border-radius: 8px;
          border: 2px dashed var(--border-color);
        }

        .light .connection-string-section {
          background: #f8f9fa;
          border-color: #dee2e6;
        }

        .dark .connection-string-section {
          background: #404040;
          border-color: #555;
        }

        .connection-string-input {
          font-family: "Consolas", "Monaco", monospace;
          font-size: 0.9rem;
          resize: vertical;
        }

        .divider {
          text-align: center;
          margin: 24px 0;
          position: relative;
          display: flex;
          align-items: center;
          justify-content: center;
        }

        .divider::before,
        .divider::after {
          content: "";
          flex: 1;
          height: 1px;
          background: var(--border-color);
        }

        .divider span {
          background: var(--bg-primary);
          padding: 0 16px;
          color: var(--text-secondary);
          font-size: 0.9rem;
          white-space: nowrap;
        }

        .form-group {
          margin-bottom: 20px;
        }

        .form-label {
          font-weight: 500;
          margin- ;
     : flex;
    n-items: center;
g: 6px;
         .form-label.required::after {
          content: "*";
          color: #dc3545;
          margin-left: 2px;
        }

        .label-icon {
          font-size: 0.9rem;
        }

        .form-control {
          border-radius: 6px;
          boeid var(--border-color);
          padding: 10px 12px;
          transition: all 0.2s ease;
          /* 添加更流畅的过渡效果 */
          transform: translateZ(0); /* 启用硬件加速 */
          backface-visibility: hidden; /* 防止闪烁 */
        }

        .light .form-control {
          background: #fff;
          color: #333;
          border-color: #ced4da;
        }

        .dark .form-control {
          background: #404040;
          color: #fff;
          border-color: #555;
        }

        .form-control:focus {
          outline: none;
          border-color: #0d6efd;
          box-shadow: 0 0 0 0.2rem rgba(13, 110, 253, 0.25);
          /* 添加聚焦时的微妙动画 */
          transform: translateY(-1px) translateZ(0);
        }

        .form-control:hover:not(:focus) {
          /* 悬停时的微妙效果 */
          border-color: var(--border-hover-color);
          transform: translateZ(0);
        }

        .light .form-control:hover:not(:focus) {
          --border-hover-color: #adb5bd;
        }

        .dark .form-control:hover:not(:focus) {
          --border-hover-color: #666;
        }

        .form-control.is-invalid {
          border-color: #dc3545;
          animation: shake 0.3s ease-in-out;
        }

        /* 添加错误时的抖动动画 */
        @keyframes shake {
          0%,
          100% {
            transform: translateX(0) translateZ(0);
          }
          25% {
            transform: translateX(-2px) translateZ(0);
          }
          75% {
      orm: translateX(2px) translateZ(0);
          }
        }

        .invalid-feedback {
          display: block;
          color: #dc3545;
          font-size: 0.875rem;
     aop: 4px;
  
    .form-text {
           0.875rem;
      gp: 4px;
       .light .text-muted {
    r: #6c757d !important;
        }

        .dark .text-muted {
          color: #adb5bd !important;
        }

        .modal-footer {
          padding: 16px 24px;
          border-top: 1px solid var(--border-color);
          display: flex;
          justify-content: flex-end;
          gap: 12px;
        }

        .light .modal-footer {
          background: #f8f9fa;
          border-top-color: #dee2e6;
        }

        .dark .modal-footer {
          background: #353535;
          border-top-color: #555;
        }

        .btn {
          padding: 8px 16px;
          border-radius: 6px;
          font-weight: 500;
          transition: all 0.2s ease;
          display: flex;
          align-items: center;
          gap: 6px;
          /* 优化按钮动画性能 */
          transform: translateZ(0);
          backface-visibility: hidden;
          position: relative;
          overflow: hidden;
        }

        .btn-icon {
         ze: 0.9rem;
          transition: transform 0.2s ease;
        }

        .btn:hover {
          transform: translateY(-1px) translateZ(0);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }

        .btn:hover .btn-icon {
          transform: scale(1.1);
        }

        .btn:active {
   form: translelateZ(0);
          transititrm 0.1s ease;
  
    /* 按钮点击    .btn::before {
       n "";
          position: absolute;
          top: 50%;
          left: 50%;
          width: 0;
          height: 0;
          border-radius: 50%;
          background: rgba(255, 255, 255, 0.3);
          transform: translate(-50%, -50%);
          transition: width 0.3s ease, height 0.3s ease;
          pointer-events: none;
        }

        .btn:active::before {
          width: 100%;
          height: 100%;
        }

        /* --- Overrides & enhancements for a more coordinated look --- */
        .connection-string-section {
          margin-bottom: 24px;
          padding: 20px;
          border-radius: 12px;
          border: 2px dashed var(--border-color);
          position: relative;
          transition: all 0.3s ease;
        }
        .connection-string-section:hover {
          /* 移除颜色变化，只保留基本的交互反馈 */
          /* border-color: var(--primary-color); */
          /* transform: translateY(-1px); */
          /* box-shadow: 0 4px 12px rgba(13, 110, 253, 0.08); */
        }
        .light .connection-string-section { background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%); }
        .dark .connection-string-section { background: linear-gradient(135deg, #404040 0%, #353535 100%); }

        .connection-string-label { display:flex; align-items:center; gap:8px; margin-bottom:12px; font-weight:600; }
        .label-badge { background: linear-gradient(135deg,#0d6efd,#0056b3); color:#fff; font-size:0.75rem; padding:2px 8px; border-radius:12px; font-weight:500; }
        .connection-input-wrapper { position: relative; }

        .connection-string-input {
          font-family: "SF Mono","Monaco","Consolas", monospace;
          font-size: 0.9rem; line-height: 1.5;
          padding: 12px 16px; border-radius: 8px;
          border: 2px solid var(--input-border); background: var(--input-bg);
          min-height: 80px; max-height: 160px; overflow: hidden; resize: none;
          transition: all 0.3s ease;
        }
        .light .connection-string-input { --input-bg:#fff; --input-border:#e9ecef; }
        .dark .connection-string-input { --input-bg:#2d2d2d; --input-border:#495057; }
        .connection-string-input:focus { border-color:#0d6efd; box-shadow:0 0 0 0.2rem rgba(13,110,253,0.2); transform: translateY(-1px); }
        .connection-string-input.has-content { border-color:#28a745; }

        .custom-placeholder { position:absolute; top:12px; left:16px; right:16px; pointer-events:none; opacity:0.6; font-family:"SF Mono","Monaco","Consolas", monospace; font-size:0.85rem; line-height:1.5; }
        .placeholder-line{ margin-bottom:4px; }
        .placeholder-params{ margin-bottom:6px; padding-left:20px; }
        .placeholder-divider{ text-align:center; margin:6px 0; font-size:0.8rem; color:var(--text-secondary); }
        .placeholder-protocol{ color:#6f42c1; font-weight:600; }
        .placeholder-host{ color:#0d6efd; font-weight:500; }
        .placeholder-path{ color:#28a745; font-weight:500; }
        .placeholder-query{ color:#fd7e14; font-size:0.8rem; }

        .input-status-indicator{ position:absolute; top:8px; right:12px; }
        .status-success, .status-error{ display:flex; align-items:center; gap:4px; padding:4px 8px; border-radius:12px; font-size:0.75rem; font-weight:500; }
        .status-success{ background:rgba(40,167,69,0.1); color:#28a745; border:1px solid rgba(40,167,69,0.2); }
        .status-error{ background:rgba(220,53,69,0.1); color:#dc3545; border:1px solid rgba(220,53,69,0.2); }
        .status-icon{ font-size:0.8rem; }

        .enhanced-error{ display:flex; align-items:center; gap:6px; margin-top:8px; padding:8px 12px; background:rgba(220,53,69,0.1); border:1px solid rgba(220,53,69,0.2); border-radius:6px; }
        .error-icon{ font-size:0.9rem; }
        .form-help{ display:flex; align-items:center; gap:6px; margin-top:8px; font-size:0.85rem; }
        .help-icon{ font-size:0.9rem; }

        /* Fix broken styles */
        .form-label{ font-weight:500; margin-bottom:6px; display:flex; align-items:center; gap:6px; }
        .form-control{ border-radius:6px; border:1px solid var(--border-color); padding:10px 12px; transition:all 0.2s ease; transform:translateZ(0); backface-visibility:hidden; }
        .invalid-feedback{ display:block; color:#dc3545; font-size:0.875rem; margin-top:4px; }
        .form-text{ font-size:0.875rem; margin-top:4px; }

        /* CSS变量定义 */
        .light {
          --bg-primary: #fff;
          --bg-secondary: #f8f9fa;
          --text-primary: #333;
          --text-secondary: #6c757d;
          --border-color: #dee2e6;
        }

        .dark {
          --bg-primary: #2d2d2d;
          --bg-secondary: #404040;
          --text-primary: #fff;
          --text-secondary: #adb5bd;
          --border-color: #555;
        }
      `}</style>
    </div>
  );
}
